//
//  EmoticonManager.swift
//  EmojiKeyboard
//
//  Created by ZhangZiang on 15/12/27.
//  Copyright © 2015年 ZhangZiang. All rights reserved.
//

import UIKit

//从plist中加载数据
class EmoticonManager: NSObject {

    //定义单例
    static let sharedEmoticonManager = EmoticonManager()

    //把text字符串转换成表情富文本字符串
    func textStringToEmoticonImageString(text : String, font : UIFont) -> NSAttributedString {
        
        //因为 [ ] 是关键字,所以要在前面加 \\ 转义一下
        let pattern = "\\[.*?\\]"
        
        let regEx = try! NSRegularExpression(pattern: pattern, options: [])
        
        let results = regEx.matchesInString(text, options: [], range: NSRange(location: 0, length: text.characters.count))
        
        let strMu = NSMutableAttributedString(string: text)
        //要倒序,否则图片会错位
        var index = results.count - 1
        
        while index>=0 {
            let result = results[index]
            
            let range = result.rangeAtIndex(0)
            
            //截取表情文字
            let subStr = (text as NSString).substringWithRange(range)
            
            if let emoti = getEmoticonFromSubString(subStr) {
            
           let imageText =  EmoticonTextAttachment().emoticonTextToImageText(emoti, font: font)
                
                //将对应文字换成富文本图片
                strMu.replaceCharactersInRange(range, withAttributedString: imageText)
            }

            
            index--
        }
        

        return strMu
    }
    
    private func getEmoticonFromSubString(subStr : String) -> Emoticon? {
        
        for p in packages {
            //MARK: filter是滤镜,会返回一个合适条件的数组(可能有空数组)
            let ems = p.emoticon.filter({ (em) -> Bool in
                //返回一个过滤条件
                return em.chs == subStr
            })
            
            if ems.count != 0 {
                return ems.last
            }
        }
        
        return nil
    }
    
    lazy var packages = [EmoticonPackages]()
    
    override init() {
        super.init()
        loadData()
    }
    
    private func loadData() {
        let path = NSBundle.mainBundle().pathForResource("emoticons.plist", ofType: nil, inDirectory: "Emoticons.bundle")
        
        guard let filePath = path else {
            print("目录不存在")
            return
        }
        
        let dict = NSDictionary(contentsOfFile: filePath)
        
        let arr = dict!["packages"] as! [[String : AnyObject]]
        
        for item in arr {
            let id = item["id"] as! String
            loadEmoticonGroups(id)
        }
    }
    
    private func loadEmoticonGroups(id : String) {
        
        let path = NSBundle.mainBundle().pathForResource("Info.plist", ofType: nil, inDirectory: "Emoticons.bundle/" + id)
        guard let filePath = path else {
            print("no filepath")
            return
        }
        
        let dict = NSDictionary(contentsOfFile: filePath)!
        
        //实例化模型
        
        let group_name_cn = dict["group_name_cn"] as! String
        let emoticons = dict["emoticons"] as! [[String : String]]
        
        let p = EmoticonPackages(id: id, group_name_cn: group_name_cn, emoticons: emoticons)
        
        packages.append(p)
    }
}


